<template>
  <!-- 真警dialog-->
  <el-dialog
    title="完成处置"
    :visible.sync="isShow"
    size="small"
    @open="openFunc"
    @close="close"
    :before-close="resetFun"
    class="dialog-class1"
  >
    <el-form
      :model="ruleForm"
      ref="ruleForm"
      :rules="rules"
      label-width="120px"
    >
      <el-row style="margin-bottom: 20px">
        <el-col :span="12">
          <el-form-item label="是否处理完成：" class="small" prop="ifFinish">
            <el-radio-group
              v-model="ruleForm.ifFinish"
              v-if="orderData.rollbackFlag === '1'"
            >
              <el-radio label="2">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row v-if="ruleForm.ifFinish === '2'">
        <el-col :span="12"
                class="input">
          <el-form-item label="处置环节："
                        prop="flowLink">
            <el-select v-model="ruleForm.flowLink"
                       clearable
                       @change="getUserId"
                       @visible-change="selectNextLinkList"
                       placeholder="请选择"
                       style="width:100%">
              <el-option v-for="item in nextLinkList"
                         :key="item.linkId"
                         :label="item.linkName"
                         :value="item.curLink">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="ruleForm.ifFinish === '2' && ruleForm.flowLink !== 6">
        <el-col :span="12">
          <el-form-item label="处理人员："
                        :prop="ruleForm.flowLink === 6 ? '': 'userId'">
            <el-select v-model="ruleForm.userId"
                       allow-create
                       filterable
                       multiple
                       @change="getUserName"
                       placeholder="请选择"
                       style="width:100%">
              <el-option v-for="item in userList"
                         :key="item.userId"
                         :label="item.userName"
                         :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row v-if="ruleForm.ifFinish === '0'">
        <el-col :span="12" class="input">
          <el-form-item label="回退环节：" prop="outFlowLink">
            <el-select
              v-model="ruleForm.outFlowLink"
              clearable
              size="medium"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in backLinkList"
                :key="item.linkId"
                :label="item.linkName"
                :value="item.linkId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" class="textareaClass">
          <el-form-item label="处置说明：" class="small">
            <el-input
              type="textarea"
              v-model="ruleForm.desc"
              placeholder="请描述..."
              rows="8"
              size="small"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="submitFun('ruleForm')" class="submitClass"
        >确 定</el-button
      >
      <el-button @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { rollBack } from "@/api/modules/eventManagement/eventCheck";
import {
  queryFlowLink,
  queryRollbackLink,
  submitOrderApproveInfo,
  signSubmitOrderApproveInfo,
  queryNextLink,
} from "@/api/modules/eventManagement/eventDispatch";
import { getFlow } from "@/api/modules/eventManagement/getFlowId";

export default {
  name: "allDispatchDialog",
  props: ["destoryDialog", "orderId", "isShow", "orderData"],
  data() {
    return {
      ruleForm: {
        ifFinish: "2",
        flowLink: "",
        outFlowLink: "",
        userId: [],
        desc: "",
      },
      flowId: "",
      usersId: [],
      usersName: [],
      visible: true,
      desc: "",
      userList: [],
      nextLinkList: [],
      backLinkList: [],
      rules: {
        ifFinish: [
          { required: true, message: "请选择", trigger: ["blur", "change"] },
        ],
        flowLink: [
          {
            required: true,
            message: "请选择处置环节",
            trigger: ["blur", "change"],
          },
        ],
        outFlowLink: [
          {
            required: true,
            message: "请选择回退环节",
            trigger: ["blur", "change"],
          },
        ],
        org: [
          {
            required: true,
            message: "请选择调度部门",
            trigger: ["blur", "change"],
          },
        ],
        userId: [
          {
            required: true,
            message: "请选择调度人员",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  methods: {
    getUserName(ids) {
      this.usersId = [];
      this.usersName = [];
      let selectInfo = {};
      for (let i in ids) {
        selectInfo = this.userList.find((item) => item.userId == ids[i]);
        this.usersId.push(selectInfo.userId);
        this.usersName.push(selectInfo.userName);
      }
    },
    openFunc() {
      this.init();
    },
    isFinishChange() {
      this.ruleForm.flowLink = "";
      this.ruleForm.userId = [];
      this.ruleForm.outFlowLink = "";
    },
    //获取操作人员列表
    getUserId(linkId) {
      const _this = this;
      if (!_this.ruleForm.flowLink) {
        _this.ruleForm.userId = [];
      }
      let params = {
        flowId: _this.flowId,
        linkId: linkId,
        orgId: _this.orderData.orgRecord,
      };
      queryFlowLink(params).then((res) => {
        if (res.code === 200) {
          let userName = res.data[0].userName.split(",");
          let userId = res.data[0].userId.split(",");
          let nameData = [];
          for (let i in userName) {
            nameData.push({
              userName: userName[i],
              userId: userId[i],
            });
          }
          _this.userList = nameData;
        }
      });
    },
    selectNextLinkList() {
      const _this = this;
      let params = {
        curLink: _this.orderData.linkId,
        flowId: _this.flowId,
        warningSource: _this.orderData.warningSource,
        templateId: _this.orderData.flowTemplate
      };
      queryNextLink(params).then((res) => {
        if (res.code === 200) {
          _this.nextLinkList = res.data;
        }
      });
    },
    getFlowIds(tenantId, warningSource, alarmCode) {
      const _this = this;
      console.log(888);
      getFlow({
        tenantId: tenantId,
        warningSource: warningSource,
        alarmCode: alarmCode,
      }).then((resp) => {
        if (resp.code == 200) {
          let flowFlow = tenantId + "_" + warningSource;
          // flowId = resp.data.flowId;
          _this.flowId = resp.data[flowFlow];
        } else {
          console.log("");
        }
      });
    },
    //初始化下拉框
    init() {
      const _this = this;
      if (!_this.orderData.flowId && !_this.flowId) {
        _this.getFlowIds(
          _this.orderData.tenantId,
          _this.orderData.warningSource,
          _this.orderData.warningTypeId
        );
      } else {
        _this.flowId = _this.flowId ? _this.flowId : _this.orderData.flowId;
      }
      queryRollbackLink({
        orderId: _this.orderId,
        linkId: _this.orderData.linkId,
      }).then((res) => {
        if (res.code === 200) {
          // debugger
          _this.backLinkList = res.data;
        }
      });
    },
    open() {
      this.$data.visible = true;
    },
    close() {
      this.$data.visible = false;
      this.destoryDialog();
    },
    //提交
    submitFun(formName) {
      const _this = this;
      this.$refs[formName].validate(
        (valid) => {
          if (valid) {
            if (_this.ruleForm.desc?.length > 255) {
              this.$message.warning("核实说明不能超过255字！");
              return;
            }
            let flowDataInfo = {};
            if (_this.ruleForm.ifFinish === "2") {
              for (let i = 0; i < _this.nextLinkList.length; i++) {
                let row = _this.nextLinkList[i];
                if (row.curLink == _this.ruleForm.flowLink) {
                  flowDataInfo = row;
                  break;
                }
              }
            } else {
              for (let i = 0; i < _this.backLinkList.length; i++) {
                let row = _this.backLinkList[i];
                if (row.linkId == _this.ruleForm.outFlowLink) {
                  flowDataInfo = row;
                  break;
                }
              }
            }
            //核实
            // if (_this.ruleForm.ifFinish == "2") {
            let params = {
              ...flowDataInfo,
              orderId: _this.orderData.warningOrderId,
              warningOrderId: _this.orderData.warningOrderId,
              operator: _this.$store.getters.userInfo.userId,
              orderApproveVOList: [
                {
                  approveStatus: _this.ruleForm.ifFinish, //0:审批失败 1:待审批 2:审批通过
                  approveResult: _this.ruleForm.desc,
                },
              ],
              voice: "",
            };
            params.ifFinish = _this.ruleForm.ifFinish;
            // params.linkId = _this.orderData.linkId;
            // params.userId = _this.ruleForm.userId.toString();
            params.isNextLink = "2";
            params.isSign = flowDataInfo.signFlag;
            // params.isSign = '2';
            params.processDTOList = [];
            for (let i in _this.usersId) {
              params.processDTOList.push({
                processId: _this.usersId[i],
                processName: _this.usersName[i],
                groupId: "",
              });
            }
            params.outFlowLink = _this.ruleForm.outFlowLink;
            if (_this.ruleForm.ifFinish === "2") {
              params.linkId = "6";
              signSubmitOrderApproveInfo(params).then((resp) => {
                if (resp && resp.code == 200) {
                  this.$message.success("核实成功");
                  this.$router.push({ path: "/event" });
                } else {
                  this.$message.error(resp.mess);
                }
              });
            } else {
              params.linkId = flowDataInfo.linkId;
              rollBack(params).then((resp) => {
                if (resp && resp.code == 200) {
                  this.$message.success("回退成功");
                  this.$router.push({ path: "/event" });
                } else {
                  this.$message.warning(resp.msg);
                }
              });
            }
          }
          this.$emit("handledispatchCancelFun", false);
        }
        // }
      );
    },
    resetFun() {
      this.$emit("handledispatchCancelFun", false);
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-row {
  margin-bottom: 1.5%;
}
/deep/ .el-upload--picture-card {
  border-radius: 5px;
}
/deep/ .el-form-item__error {
    position: relative;
}
/deep/ .el-form-item__error {
  position: relative;
}
/deep/ .submitClass {
  background: #ff6a6c !important;
  color: #ffffff !important;
}
/deep/ .el-select__tags {
  overflow: auto;
}
</style>
